﻿/*
 * Created by SharpDevelop.
 * User: Михаил
 * Date: 08.12.2014
 * Time: 20:14
 * 
 * To change this template use Tools | Options | Coding | Edit Standard Headers.
 */
using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Windows.Forms;
using Region.Utils;
using System.Data;
using System.Data.Linq;
using System.Linq;
namespace Invent
{
	/// <summary>
	/// Description of MainForm.
	/// </summary>
	public partial class MainForm : Form
	{
		DatabaseInvent m_db;
		PrintForm410 formp410;
		public MainForm(DatabaseInvent db)
		{
			m_db = db;
			//
			// The InitializeComponent() call is required for Windows Forms designer support.
			//
			InitializeComponent();
			
			//
			// TODO: Add constructor code after the InitializeComponent() call.
			//
			ShowSelectors();
			Button1Click(this, null);
		}
		void ShowSelectors()
		{		  
		  Guid PlaceUID = Guid.Empty;
		  var siPlace = Place.SelectedItem as ListItemValue;
		  if (siPlace != null) PlaceUID = (Guid)siPlace.Value;		  
		  Place.Items.Clear();
		  Place.Items.Add(new ListItemValue(m_db.getPlaceName(Guid.Empty),Guid.Empty));
		  foreach(var r in from row in m_db.Places.AsEnumerable() orderby m_db.getPlaceName(row.Field<Guid>("PlaceUID")) select row)
		  {
		    Guid PUID = r.Field<Guid>("PlaceUID");
		    Place.Items.Add(new ListItemValue(m_db.getPlaceName(PUID),PUID));
		  }		  
		  Place.SelectedItem = new ListItemValue(m_db.getPlaceName(PlaceUID),PlaceUID);

		  Guid EmployeeUID = Guid.Empty;
		  var siEmployee = Employee.SelectedItem as ListItemValue;
		  if (siEmployee != null) EmployeeUID = (Guid)siEmployee.Value;		  
		  Employee.Items.Clear();
		  Employee.Items.Add(new ListItemValue(m_db.getEmployeeName(Guid.Empty),Guid.Empty));
		  foreach(var r in from row in m_db.Employee.AsEnumerable() orderby row.Field<String>("EmployeeName") select row)
		  {
		    Guid PUID = r.Field<Guid>("EmployeeUID");
		    Employee.Items.Add(new ListItemValue(m_db.getEmployeeName(PUID),PUID));
		  }		  
		  Employee.SelectedItem = new ListItemValue(m_db.getEmployeeName(EmployeeUID),EmployeeUID);

		  Guid DeliveryUID = Guid.Empty;
		  var siDelivery = Delivery.SelectedItem as ListItemValue;
		  if (siDelivery != null) DeliveryUID = (Guid)siDelivery.Value;		  
		  Delivery.Items.Clear();
		  Delivery.Items.Add(new ListItemValue(m_db.getDeliveryName(Guid.Empty),Guid.Empty));
		  foreach(var r in from row in m_db.Delivery.AsEnumerable() orderby row.Field<String>("DeliveryName") select row)
		  {
		    Guid PUID = r.Field<Guid>("DeliveryUID");
		    Delivery.Items.Add(new ListItemValue(m_db.getDeliveryName(PUID),PUID));
		  }		  
		  Delivery.SelectedItem = new ListItemValue(m_db.getDeliveryName(DeliveryUID),DeliveryUID);

		  String iDeviceType = DeviceType.Text;
		  DeviceType.Items.Clear();
		  DeviceType.Items.Add("");
		  foreach(String r in from row in m_db.Devices.AsEnumerable() group row by row.Field<String>("DeviceType") into r1 orderby r1.Key select r1.Key)
		    if (r !="")
		  {
		    DeviceType.Items.Add(r);
		  }		  
		  DeviceType.SelectedItem = iDeviceType;
		  
		  AccessButton();
		  //m_db.Places
		}
		void AccessButton()
		{
		  Guid PlaceUID = Guid.Empty;
		  var siPlace = Place.SelectedItem as ListItemValue;
		  if (siPlace != null) PlaceUID = (Guid)siPlace.Value;
		  Guid EmployeeUID = Guid.Empty;
		  var siEmployee = Employee.SelectedItem as ListItemValue;
		  if (siEmployee != null) EmployeeUID = (Guid)siEmployee.Value;		  
		  Guid DeliveryUID = Guid.Empty;
		  var siDelivery = Delivery.SelectedItem as ListItemValue;
		  if (siDelivery != null) DeliveryUID = (Guid)siDelivery.Value;		  

		  PrintKart.Enabled = (PlaceUID!=Guid.Empty) && (EmployeeUID!=Guid.Empty) && (DeliveryUID==Guid.Empty);
		}
		EnumerableRowCollection<DataRow> getDevListSelect()
		{
		  var query = from row in m_db.Devices.AsEnumerable() select row;
		  Guid PlaceUID = (Place.SelectedItem==null?Guid.Empty:(Guid)((ListItemValue)Place.SelectedItem).Value);
		  if (PlaceUID!=Guid.Empty)
		    query = from row in query where row.Field<Guid>("PlaceUID")==PlaceUID select row;		      
		  Guid EmployeeUID = (Employee.SelectedItem==null?Guid.Empty:(Guid)((ListItemValue)Employee.SelectedItem).Value);
		  if (EmployeeUID!=Guid.Empty)
		    query = from row in query where row.Field<Guid>("EmployeeUID")==EmployeeUID select row;		      
		  Guid DeliveryUID = (Delivery.SelectedItem==null?Guid.Empty:(Guid)((ListItemValue)Delivery.SelectedItem).Value);
		  if (DeliveryUID!=Guid.Empty)
		    query = from row in query where row.Field<Guid>("DeliveryUID")==DeliveryUID select row;		
      String iDeviceType = DeviceType.Text;
      if (iDeviceType!="")
		    query = from row in query where row.Field<String>("DeviceType")==iDeviceType select row;		
      String iInventNum = InventNum.Text;      
      if (iInventNum!="")
        query = from row in query where row.Field<String>("InventNum").Contains(iInventNum) select row;
      String iSerialNum = SerialNum.Text;      
      if (iSerialNum!="")
        query = from row in query where row.Field<String>("SerialNum").Contains(iSerialNum) select row;

      return query;
		}
		void ShowDevices(Guid SelectDeviceUID)
		{
		  listView1.Items.Clear();
		  foreach(var r in getDevListSelect())
		  {
		    var i = new ListViewItem();
		    i.Text = r.Field<String>("InventNum");
		    i.Tag = r.Field<Guid>("DeviceUID");
		    i.SubItems.Add(r.Field<String>("DeviceName"));
		    i.SubItems.Add(m_db.getEmployeeName(r.Field<Guid>("EmployeeUID")));
		    i.SubItems.Add(m_db.getPlaceName(r.Field<Guid>("PlaceUID")));
		    
		    i.SubItems.Add(r.Field<String>("SerialNum"));
		    listView1.Items.Add(i);
		  }		  
		}
		void MainFormLoad(object sender, EventArgs e)
		{
		  
		}
		
		void Button1Click(object sender, EventArgs e)
		{
		  ShowDevices(Guid.Empty);
		}
    void ButtonAddPlaceClick(object sender, EventArgs e)
    {
      var siPlace = Place.SelectedItem as ListItemValue;
      if (siPlace!=null)
      {
        var PlaceUID = (Guid)siPlace.Value;
        var form = new PlaceEdit(m_db,PlaceUID);
        form.ShowDialog();
        ShowSelectors();
      }
    }
    void ButtonAddEmployeeClick(object sender, EventArgs e)
    {
      var siEmployee = Employee.SelectedItem as ListItemValue;
      if (siEmployee!=null)
      {
        var EmployeeUID = (Guid)siEmployee.Value;
        var form = new EmployeeEdit(m_db,EmployeeUID);
        form.ShowDialog();
        ShowSelectors();
      }
    }
    void ButtonAddDeliveryClick(object sender, EventArgs e)
    {
      var siDelivery = Delivery.SelectedItem as ListItemValue;
      if (siDelivery!=null)
      {
        var DeliveryUID = (Guid)siDelivery.Value;
        var form = new DeliveryEdit(m_db,DeliveryUID);
        form.ShowDialog();
        ShowSelectors();
      }
    }
    void ListView1DoubleClick(object sender, EventArgs e)
    {
      if (listView1.SelectedItems.Count>0)
      {
        var DeviceUID = (Guid)listView1.SelectedItems[0].Tag;
        var form = new DeviceEdit(m_db,DeviceUID);
        form.ShowDialog();
        ShowDevices(DeviceUID);
        
      }
    }
    void Button2Click(object sender, EventArgs e)
    {
      	Guid iDeliveryUID = Guid.Empty;
  		  var siDelivery = Delivery.SelectedItem as ListItemValue;
  		  if (siDelivery != null) iDeliveryUID = (Guid)siDelivery.Value;		
  		  Guid iEmployeeUID = Guid.Empty;
  		  var siEmployee = Employee.SelectedItem as ListItemValue;
  		  if (siEmployee != null) iEmployeeUID = (Guid)siEmployee.Value;		  
  		  Guid iPlaceUID = Guid.Empty;
  		  var siPlace = Place.SelectedItem as ListItemValue;
  		  if (siPlace != null) iPlaceUID = (Guid)siPlace.Value;		
  		  String iDeviceType = DeviceType.Text;
        DataRow row = m_db.newDevice("Инв. номер","Наименование",iPlaceUID,iDeliveryUID,iEmployeeUID,iDeviceType,"");
			  var DeviceUID = row.Field<Guid>("DeviceUID");        
			  var form = new DeviceEdit(m_db,DeviceUID);
        form.ShowDialog();
        ShowDevices(DeviceUID);  
    }
    
    void Button3Click(object sender, EventArgs e)
    {
      Int32 Num=1;
      var DeliveryList = new Dictionary<Guid,Int32>();
      var PlaceList = new Dictionary<Guid,Int32>();
      var DeviceTable  = new List<Dictionary<string, object>>();
      		  foreach(var r in getDevListSelect())
		  {
      	var row = new Dictionary<string, object>();	
      	row["%DeviceTable%"] = Num++;
      	row["%DeviceName%"] = r.Field<String>("DeviceName");
        row["%DeviceType%"] = r.Field<String>("DeviceType");
        row["%DeviceModel%"] = r.Field<String>("DeviceModel");
        row["%InventNum%"] = r.Field<String>("InventNum");
        row["%SerialNum%"] = r.Field<String>("SerialNum");
        row["%Place%"] = m_db.getPlaceName(r.Field<Guid>("PlaceUID"));
        row["%Employee%"] = m_db.getEmployeeName(r.Field<Guid>("EmployeeUID"));
        row["%Delivery%"] = m_db.getDeliveryName(r.Field<Guid>("DeliveryUID"));
      	DeviceTable.Add(row);
      	var deliUID = r.Field<Guid>("DeliveryUID");
        if (!DeliveryList.ContainsKey(deliUID)) DeliveryList[deliUID] = 0;
        DeliveryList[deliUID] = DeliveryList[deliUID] + 1;
        var plUID = r.Field<Guid>("PlaceUID");
        if (!PlaceList.ContainsKey(plUID)) PlaceList[plUID] = 0;
        PlaceList[plUID] = PlaceList[plUID] + 1;
		  }      
      Num=1;
      var DeliveryTable  = new List<Dictionary<string, object>>();      		  
      foreach(var r1 in DeliveryList )
        foreach(var r in from row in m_db.Delivery.AsEnumerable() where row.Field<Guid>("DeliveryUID")==r1.Key select row )
		  {
      	var row = new Dictionary<string, object>();	
      	row["%DeliveryTable%"] = Num++;
      	row["%DeliveryName%"] = r.Field<String>("DeliveryName");
      	row["%DeliveryOrganization%"] = r.Field<String>("DeliveryOrganization");
      	if (r.IsNull("DeliveryDate"))
      	  row["%DeliveryDate%"] = "";
      	else
      	  row["%DeliveryDate%"] = r.Field<DateTime>("DeliveryDate");
      	row["%DeviceCount%"] = r1.Value;
      	DeliveryTable.Add(row);
		  }
      Num=1;
      var PlaceTable  = new List<Dictionary<string, object>>();      		  
      foreach(var r1 in PlaceList )
        foreach(var r in from row in m_db.Places.AsEnumerable() where row.Field<Guid>("PlaceUID")==r1.Key select row )
		  {
      	var row = new Dictionary<string, object>();	
      	row["%PlaceTable%"] = Num++;
      	row["%PlaceName%"] = m_db.getPlaceName(r.Field<Guid>("PlaceUID"));      	
      	row["%DeviceCount%"] = r1.Value;
      	PlaceTable.Add(row);
		  }      
 		  m_db.ExportXLSX("ListDevice.xltx",
                 new Dictionary<string, object>(),
                 new Dictionary<string, List<Dictionary<string, object>>>{
                   {"%DeviceTable%",DeviceTable},
                   {"%DeliveryTable%",DeliveryTable},
                   {"%PlaceTable%",PlaceTable}
                 });

    }
    void Button4Click(object sender, EventArgs e)
    {
		  
		  Guid PlaceUID = (Place.SelectedItem==null?Guid.Empty:(Guid)((ListItemValue)Place.SelectedItem).Value);
		  Guid EmployeeUID = (Employee.SelectedItem==null?Guid.Empty:(Guid)((ListItemValue)Employee.SelectedItem).Value);
		  Guid DeliveryUID = (Delivery.SelectedItem==null?Guid.Empty:(Guid)((ListItemValue)Delivery.SelectedItem).Value);
		  if (PlaceUID==Guid.Empty) return;
		  if (EmployeeUID==Guid.Empty) return;
		  if (DeliveryUID!=Guid.Empty) return;
		  var query = from row in m_db.Devices.AsEnumerable()
        where row.Field<Guid>("PlaceUID")==PlaceUID && row.Field<Guid>("EmployeeUID")==EmployeeUID    
		    select row;
		  var col = new Dictionary<string, object>();
		  col["%Place%"] = m_db.getPlaceName(PlaceUID);
		  col["%Employee%"] = m_db.getPlaceName(EmployeeUID);
		  Int32 Num=1;
      var DeviceTable  = new List<Dictionary<string, object>>();
      foreach(var r in query)
		  {
      	var row = new Dictionary<string, object>();	
      	row["%DeviceTable%"] = Num++;
      	row["%DeviceName%"] = r.Field<String>("DeviceName");
        row["%DeviceType%"] = r.Field<String>("DeviceType");
        row["%DeviceModel%"] = r.Field<String>("DeviceModel");
        row["%InventNum%"] = r.Field<String>("InventNum");
        row["%SerialNum%"] = r.Field<String>("SerialNum");
        row["%Place%"] = m_db.getPlaceName(r.Field<Guid>("PlaceUID"));
        row["%Employee%"] = m_db.getEmployeeName(r.Field<Guid>("EmployeeUID"));
        row["%Delivery%"] = m_db.getDeliveryName(r.Field<Guid>("DeliveryUID"));
      	DeviceTable.Add(row);
		  }

      m_db.ExportXLSX("Kart.xltx",col,
                 new Dictionary<string, List<Dictionary<string, object>>>{{"%DeviceTable%",DeviceTable}});

    }
    void PlaceSelectedIndexChanged(object sender, EventArgs e)
    {
      AccessButton();
    }
    void EmployeeSelectedIndexChanged(object sender, EventArgs e)
    {
      AccessButton();
    }
    void DeliverySelectedIndexChanged(object sender, EventArgs e)
    {
      AccessButton();
    }
		
		void CreateFromClick(object sender, EventArgs e)
		{    
  		  if (listView1.SelectedItems.Count==0) return;
  		  Guid iDeviceUID = (Guid)listView1.SelectedItems[0].Tag;
  		  DataRow rowFrom = (from r in m_db.Devices.AsEnumerable() where r.Field<Guid>("DeviceUID")==iDeviceUID select r).Single();
  		  
        DataRow row = m_db.newDevice(rowFrom.Field<String>("InventNum"),
  		                               rowFrom.Field<String>("DeviceName"),
  		                               rowFrom.Field<Guid>("PlaceUID"),
  		                               rowFrom.Field<Guid>("DeliveryUID"),
  		                               rowFrom.Field<Guid>("EmployeeUID"),
  		                               rowFrom.Field<String>("DeviceType"),
  		                               rowFrom.Field<String>("DeviceModel"));
  		  row.SetField<String>("SerialNum",rowFrom.Field<String>("SerialNum"));
			  var DeviceUID = row.Field<Guid>("DeviceUID");        
			  var form = new DeviceEdit(m_db,DeviceUID);
        form.ShowDialog();
        ShowDevices(DeviceUID);  
		}
    void PrintForm410ButtonClick(object sender, EventArgs e)
    {
      if (formp410==null)
        formp410 = new PrintForm410(this,m_db);
      formp410.Show();
      for(Int32 i=0;i<listView1.SelectedItems.Count;i++)      
        formp410.AddDevice((Guid)listView1.SelectedItems[i].Tag);
      
        
    }
    void MainFormFormClosed(object sender, FormClosedEventArgs e)
    {
      if (formp410!=null)
        formp410.Close();
    }
    void MainFormMove(object sender, EventArgs e)
    {
      if (formp410!=null)
        formp410.setMove();
    }
	}
}
